package com.hxh.wechat.api

import com.hxh.wechat.constant.GlobalConstant
import com.hxh.wechat.util.HttpUtil
import com.hxh.wechat.util.toFormBody
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import java.io.DataOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL

class FileApi {
    companion object {
        data class User(val username: String, val password: String, val cid: String)

        /**
         * 用户模块一级路径
         */
        private const val BASE_URL: String = "file/";

        /**
         * 用户模块二级路径
         */

        //注册登录接口
        private const val UPLOAD: String = "uploadImage";


        fun uploadFile(filePath: String): String? {
            val client = OkHttpClient()
            val file = File(filePath)
            val requestBody = MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart(
                    "file",
                    file.name,
                    RequestBody.create("multipart/form-data".toMediaTypeOrNull(), file)
                )
                .build()

            val request = Request.Builder()
                .url(HttpUtil.BASE_URL + "/" + BASE_URL + UPLOAD)
                .post(requestBody)
                .build()

            try {
                client.newCall(request).execute().use { response ->
                    if (!response.isSuccessful) throw IOException("Unexpected code $response")
                    return response.body?.string()
                }
            } catch (e: IOException) {
                e.printStackTrace()
                return null
            }
        }
    }
}